package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.security.Security;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo  trade() {
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);//获取用户的购物车列表
        if (R.FAIL==cartCheckedList.getCode())//获取失败
        {
            throw new ServiceException(cartCheckedList.getMsg());
        }
            List<CartInfo> data = cartCheckedList.getData();//购物车列表
            if (CollectionUtils.isEmpty(data)){
                throw new ServiceException("请选择商品");
            }
            List<OrderItem> orderItemList = null;
            BigDecimal amount = new BigDecimal(0);
            if (!CollectionUtils.isEmpty(data)){
                 orderItemList = data.stream().map(cartInfo -> {
                    OrderItem orderItem = new OrderItem();
                    BeanUtils.copyProperties(cartInfo, orderItem);
                    orderItem.setSkuPrice(cartInfo.getSkuPrice());
                    return orderItem;
            }).collect(Collectors.toList());
            }
            for (OrderItem orderItem : orderItemList) {
                amount = amount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
            }

        String userTradeKey = "user:tradeNo:" + userId;//用户的订单编号key
        String s = UUID.randomUUID().toString().replaceAll("-", "");//生成订单编号
        redisTemplate.opsForValue().set(userTradeKey, s, 10, TimeUnit.MINUTES);//订单编号有效期10分钟
        TradeVo tradeVo = new TradeVo();//订单信息
        tradeVo.setTradeNo(s);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(amount);
        return tradeVo;
    }

    @Transactional(rollbackFor = Exception.class )
    @Override
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String tradeNoKey = "user:tradeNo:" + userId;
        String tradeNo = orderForm.getTradeNo();
        String redisTradeN = (String) redisTemplate.opsForValue().get(tradeNoKey);//获取redis中的交易号
        //判断交易号是否一致
        if (!tradeNo.equals(redisTradeN)) {
            throw new RuntimeException("订单已提交");
        }
        //删除redis中的交易号
        redisTemplate.delete(tradeNoKey);
        //判断表单参数是否为空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();//订单商品列表
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new RuntimeException("请选择结算商品");
        }
        //3.校验价格是否一致，不一致更新价格,取消下单
        List<Long> list = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceList = remoteProductService.getSkuPriceList(list, SecurityConstants.INNER);
        if (R.FAIL == skuPriceList.getCode()){
            throw new RuntimeException(skuPriceList.getMsg());
        }
        List<SkuPrice> data = skuPriceList.getData();
        Map<Long, BigDecimal> collect = data.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        StringBuilder builder = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(collect.get(orderItem.getSkuId())) != 0){
                builder.append("【"+orderItem.getSkuName()+"】商品价格有变动;");
            }
        }
        if (StringUtils.hasText(builder.toString())){
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw new ServiceException(builder.toString());
        }
        //4.检查与锁定库存  TODO
         List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).collect(Collectors.toList());
        R<String> stringR = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if(R.FAIL == stringR.getCode()){
            throw new ServiceException(stringR.getMsg());
        }
        String data1 = stringR.getData();
        if(StringUtils.hasText(data1)){
            throw new ServiceException(data1);
        }
        //5.保存订单(order_info\order_item\order_log)
        Long orderId = null;
        try {
            orderId = saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }
        //6.删除购物车商品。考虑一下：可以在支付后删除购物车勾选的商品。否则，下单取消，还得把商品加回购物车。
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
        //7.发送延迟消息。指定支付等待时间，如果不支付，消费者处理延迟消息就会自动取消订单，解锁库存。
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId), MqConst.CANCEL_ORDER_DELAY_TIME);
        return orderId;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus().intValue() == 0){//  订单状态orderStatus=0 说明15分钟未支付
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("超时或未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().
                eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItems);
        return orderInfo;
    }

    @Override
    public void processPaySucess(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().
                eq(OrderInfo::getOrderNo, orderNo).
                select(OrderInfo::getId, OrderInfo::getOrderStatus));//获取订单信息
        if (orderInfo.getOrderStatus().intValue()==0){
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }

    private Long saveOrder(OrderForm orderForm) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        //1.保存订单数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));//订单总金额
        }
        orderInfo.setTotalAmount(totalAmount); //实付总价格 (减掉优惠钱 + 运费的钱)
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount); //商品总价格(不包括优惠卷和运费)
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        //orderInfo.setCreateTime(new Date());
        orderInfoMapper.insert(orderInfo); //主键回填 insert：MyBatis 内置的插入方法，由框架动态实现。
        Long orderId = orderInfo.getId();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem);
        }
        //3.保存订单日志数据
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setProcessStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);
        return orderId;

    }

}